using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Awaiter;
using Nsb.Classes;
using YoshiBase.Classes;
using jQueryApi;

namespace Yoshi.Classes
{
    [IgnoreNamespace]
    public class MagneticData : SavableData
    {
        private static readonly string PartitionKey = Uri.DbPath("lists");
        private readonly string RowKey;
        public Dictionary<string, MagList> Records = new Dictionary<string, MagList>();
        private MagList _record;

        public MagneticData()
        {
            RowKey = My.id;
        }

        public MagList DataRecord
        {
            get { return _record; }
        }

        public YoshiUser My
        {
            get { return Master.Profile.My; }
        }

        public string RecordName
        {
            get { return Script.IsValue(_record) ? _record.name : null; }
        }

        public Dictionary NameList()
        {
            return DropMenu.Listify(
                Records,
                delegate(object a, object b) { return ((MagList) a).modified_time < ((MagList) b).modified_time ? 1 : -1; },
                delegate(Dictionary d, object o) { d[((MagList) o).name] = (new Date(((MagList) o).modified_time)).Format("yyyy-MM-dd : ") + ((MagList) o).name; }
                );
        }

        //public bool Saved
        //{
        //    get
        //    {
        //        _saved = Storage.CompareObjects(ScoopData(), _record);
        //        if (!_saved && _record != null)
        //            _record.modified_time = (new Date()).GetTime();
        //        return _saved;
        //    }
        //    set { _saved = value; }
        //}

        public void LoadRecordsAw(Await awp)
        {
            new Await()
                .AddDl(delegate(Await aw) { RetrieveBlobAw(aw, PartitionKey, RowKey); })
                .HandleDl(Exceptions.BlobLoadError,
                          delegate(Await aw)
                          {
                              Inform.Trace("LoadRecordsAw() HandleDl");
                              aw.Done();
                          }
                )
                .AddDx(
                    delegate(Await aw)
                    {
                        Inform.Trace("LoadRecordsAw() 2");
                        Dictionary<string, MagList> records = (Dictionary<string, MagList>) aw[ResultRx];
                        if (Script.IsValue(records))
                        {
                            Records = records;
                            Saved(true);
                        }
                    })
                .Commit(awp);
        }

        public void SaveRecords()
        {
            Saved(true);
            StoreBlobAw(Await.AsyncAw, PartitionKey, RowKey, ResultRx, Records);
            UpdatePage();
        }

        public void LoadRecord(string name)
        {
            name = name.ToLowerCase();
            _record = Script.Value(Records[name], new MagList(null, null));
            Saved(true);
        }

        public void SaveRecord()
        {
            // Get the list
            MagList list = ScoopData();

            // Save the list
            if (Script.IsValue(list))
            {
                // If the master list is null create it
                _record = list;
                Records[_record.name.ToLowerCase()] = _record;
                SaveRecords();
            }
        }

        /// <summary>
        /// Scoops the data from the manipulator, usually the UI
        /// </summary>
        /// <returns>an object representation of the data</returns>
        private MagList ScoopData()
        {
            jQueryObject magEl = jQuery.Select(".MagName");
            if (magEl.Length > 0)
            {
                string name = magEl.Plugin<Jewl>().GetFValueString();
                if (!String.IsNullOrEmpty(name))
                {
                    MagList list = new MagList(name, jQuery.Select("#MagList textarea"));
                    int now = (new Date()).GetTime();
                    list.modified_time = Script.Value(_record != null ? _record.modified_time : 0, now);
                    list.create_time = Script.Value(_record != null ? _record.create_time : 0, now);
                    return list;
                }
            }
            return null;
        }

        public void EmptyRecord()
        {
            _record = null;
        }

        public void DeleteList(string name)
        {
            name = name.ToLowerCase();
            if (Records.ContainsKey(name))
            {
                Records.Remove(name);
                Saved(true);
                StoreBlobAw(Await.AsyncAw, PartitionKey, RowKey, ResultRx, Records);
                UpdatePage();
            }
        }
    }
}